In this project, you'll use generative adversarial networks to generate new images of faces.
You'll be using two datasets in this project:
Since the celebA dataset is complex and you're doing GANs in a project for the first time, we want you to test your neural network on MNIST before CelebA. Running the GANs on MNIST will allow you to see how well your model trains sooner.
If you're using FloydHub, set data_dir to "/input" and use the FloydHub data ID "R5KrjnANiKVhLWAkpXhNBe".
# 5th Project of the Deep Learning Foundation Udacity's Nanodegree
# Author: Daniel Abrantes Formiga
data_dir = './data'
# FloydHub - Use with data ID "R5KrjnANiKVhLWAkpXhNBe"
#data_dir = '/input'
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import helper
helper.download_extract('mnist', data_dir)
helper.download_extract('celeba', data_dir)
show_n_images = 25
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
%matplotlib inline
import os
from glob import glob
from matplotlib import pyplot
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'mnist/*.jpg'))[:show_n_images], 28, 28, 'L')
pyplot.imshow(helper.images_square_grid(mnist_images, 'L'), cmap='gray')
The CelebFaces Attributes Dataset (CelebA) dataset contains over 200,000 celebrity images with annotations. Since you're going to be generating faces, you won't need the annotations. You can view the first number of examples by changing show_n_images.
show_n_images = 50
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
mnist_images = helper.get_batch(glob(os.path.join(data_dir, 'img_align_celeba/*.jpg'))[:show_n_images], 28, 28, 'RGB')
pyplot.imshow(helper.images_square_grid(mnist_images, 'RGB'))
Since the project's main focus is on building the GANs, we'll preprocess the data for you. The values of the MNIST and CelebA dataset will be in the range of -0.5 to 0.5 of 28x28 dimensional images. The CelebA images will be cropped to remove parts of the image that don't include a face, then resized down to 28x28.
The MNIST images are black and white images with a single color channel while the CelebA images have 3 color channels (RGB color channel).
You'll build the components necessary to build a GANs by implementing the following functions below:
model_inputsdiscriminatorgeneratormodel_lossmodel_opttrainThis will check to make sure you have the correct version of TensorFlow and access to a GPU
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
from distutils.version import LooseVersion
import warnings
import tensorflow as tf
# Check TensorFlow Version
assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer. You are using {}'.format(tf.__version__)
print('TensorFlow Version: {}'.format(tf.__version__))
# Check for a GPU
if not tf.test.gpu_device_name():
warnings.warn('No GPU found. Please use a GPU to train your neural network.')
else:
print('Default GPU Device: {}'.format(tf.test.gpu_device_name()))
Implement the model_inputs function to create TF Placeholders for the Neural Network. It should create the following placeholders:
image_width, image_height, and image_channels.z_dim.Return the placeholders in the following the tuple (tensor of real input images, tensor of z data)
import problem_unittests as tests
def model_inputs(image_width, image_height, image_channels, z_dim):
"""
Create the model inputs
:param image_width: The input image width
:param image_height: The input image height
:param image_channels: The number of image channels
:param z_dim: The dimension of Z
:return: Tuple of (tensor of real input images, tensor of z data, learning rate)
"""
# Inputs placeholders
real_input = tf.placeholder(tf.float32, [None, image_width, image_height, image_channels], name='real_input')
z_input = tf.placeholder(tf.float32, [None, z_dim], name='z_input')
learn_rate = tf.placeholder(tf.float32, name='learning_rate')
return real_input, z_input, learn_rate
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_inputs(model_inputs)
Implement discriminator to create a discriminator neural network that discriminates on images. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "discriminator" to allow the variables to be reused. The function should return a tuple of (tensor output of the discriminator, tensor logits of the discriminator).
def discriminator(images, reuse=False):
"""
Create the discriminator network
:param images: Tensor of input image(s)
:param reuse: Boolean if the weights should be reused
:return: Tuple of (tensor output of the discriminator, tensor logits of the discriminator)
"""
# The convolutional neural network will be used due to the inputs are images
# Alpha value for leaky ReLU
alpha = 0.2
# Variable scope discriminator
with tf.variable_scope('discriminator', reuse=reuse):
# First conv layer
conv1 = tf.layers.conv2d(images, 64, 5,
strides=2,
padding='same',
kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d())
# Leaky ReLU - There is no batch normalization in the firs input layer
leak_relu1 = tf.maximum(alpha * conv1, conv1)
# Second conv layer
conv2 = tf.layers.conv2d(leak_relu1, 128, 5,
strides=2,
padding='same',
kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d())
# Batch normalizing before the leaky ReLU
batch_norm1 = tf.layers.batch_normalization(conv2, training=True)
# Leaky ReLU
leak_relu2 = tf.maximum(alpha * batch_norm1, batch_norm1)
# Third conv layer
conv3 = tf.layers.conv2d(leak_relu2, 256, 4,
strides=1,
padding='valid',
kernel_initializer=tf.contrib.layers.xavier_initializer_conv2d())
# Batch normalizing before the leaky ReLU
batch_norm2 = tf.layers.batch_normalization(conv3, training=True)
# Leaky ReLU
leak_relu3 = tf.maximum(alpha * batch_norm2, batch_norm2)
# Reshaping image
leak_relu3_dim = leak_relu3.get_shape().as_list()
reshape_dim = leak_relu3_dim[1] * leak_relu3_dim[2] * leak_relu3_dim[3]
flatten_data = tf.reshape(leak_relu3, (-1, reshape_dim))
# Dense layer
logits = tf.layers.dense(flatten_data, 1,
kernel_initializer=tf.contrib.layers.xavier_initializer())
discrim_output = tf.sigmoid(logits)
return discrim_output, logits
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_discriminator(discriminator, tf)
Implement generator to generate an image using z. This function should be able to reuse the variables in the neural network. Use tf.variable_scope with a scope name of "generator" to allow the variables to be reused. The function should return the generated 28 x 28 x out_channel_dim images.
def generator(z, out_channel_dim, is_train=True):
"""
Create the generator network
:param z: Input z
:param out_channel_dim: The number of channels in the output image
:param is_train: Boolean if generator is being used for training
:return: The tensor output of the generator
"""
# Alpha value for leaky ReLU
alpha = 0.2
with tf.variable_scope('generator', reuse=not is_train):
# Dense layer
dense_layer = tf.layers.dense(z, 4*4*512,
kernel_initializer=tf.contrib.layers.xavier_initializer())
# Reshaping the data
data_reshape = tf.reshape(dense_layer, (-1, 4, 4, 512))
# Batch normalization
batch_norm1 = tf.layers.batch_normalization(data_reshape, training=is_train)
# Leaky ReLU
leak_relu1 = tf.maximum(alpha * batch_norm1, batch_norm1)
# First transpose conv layer
conv1 = tf.layers.conv2d_transpose(leak_relu1, 256, 4,
strides=1,
padding='valid',
kernel_initializer=tf.contrib.layers.xavier_initializer())
# Batch normalization
batch_norm2 = tf.layers.batch_normalization(conv1, training=is_train)
# Leaky ReLU
leak_relu2 = tf.maximum(alpha * batch_norm2, batch_norm2)
# Second transpose conv layer
conv2 = tf.layers.conv2d_transpose(leak_relu2, 128, 5,
strides=2,
padding='same',
kernel_initializer=tf.contrib.layers.xavier_initializer())
# Batch normalization
batch_norm3 = tf.layers.batch_normalization(conv2, training=is_train)
# Leaky ReLU
leak_relu3 = tf.maximum(alpha * batch_norm3, batch_norm3)
# Third transpose conv layer
logits = tf.layers.conv2d_transpose(leak_relu3, out_channel_dim, 5,
strides=2,
padding='same',
kernel_initializer=tf.contrib.layers.xavier_initializer())
gen_output = tf.tanh(logits)
return gen_output
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_generator(generator, tf)
Implement model_loss to build the GANs for training and calculate the loss. The function should return a tuple of (discriminator loss, generator loss). Use the following functions you implemented:
discriminator(images, reuse=False)generator(z, out_channel_dim, is_train=True)def model_loss(input_real, input_z, out_channel_dim):
"""
Get the loss for the discriminator and generator
:param input_real: Images from the real dataset
:param input_z: Z input
:param out_channel_dim: The number of channels in the output image
:return: A tuple of (discriminator loss, generator loss)
"""
# Generator
gen_output = generator(input_z, out_channel_dim, is_train=True)
# Discriminator with real data
discr_real, d_logits = discriminator(input_real, reuse=False)
# Discriminator with generated data
discr_fake, d_gen_logits = discriminator(gen_output, reuse=True)
# Discriminator real data loss
d_real_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_logits, labels=tf.ones_like(discr_real) * 0.9))
# Discriminator fake data loss
d_fake_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_gen_logits, labels=tf.zeros_like(discr_fake)))
# Discriminator total loss
d_loss = d_real_loss + d_fake_loss
# Generator loss
g_loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(logits=d_gen_logits, labels=tf.ones_like(discr_fake)))
return d_loss, g_loss
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_loss(model_loss)
Implement model_opt to create the optimization operations for the GANs. Use tf.trainable_variables to get all the trainable variables. Filter the variables with names that are in the discriminator and generator scope names. The function should return a tuple of (discriminator training operation, generator training operation).
def model_opt(d_loss, g_loss, learning_rate, beta1):
"""
Get optimization operations
:param d_loss: Discriminator loss Tensor
:param g_loss: Generator loss Tensor
:param learning_rate: Learning Rate Placeholder
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:return: A tuple of (discriminator training operation, generator training operation)
"""
# Getting all the trainable variables
nn_variables = tf.trainable_variables()
# Getting the generator trainable variables
gen_variables = [var for var in nn_variables if var.name.startswith('generator')]
# Getting the discriminator trainable variables
disc_variables = [var for var in nn_variables if var.name.startswith('discriminator')]
with tf.control_dependencies(tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
# Optimizing the loss of the generator
gen_opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(g_loss,
var_list=gen_variables)
# Optimizing the loss of the discriminator
disc_opt = tf.train.AdamOptimizer(learning_rate=learning_rate, beta1=beta1).minimize(d_loss,
var_list=disc_variables)
return disc_opt, gen_opt
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_model_opt(model_opt, tf)
"""
DON'T MODIFY ANYTHING IN THIS CELL
"""
import numpy as np
def show_generator_output(sess, n_images, input_z, out_channel_dim, image_mode):
"""
Show example output for the generator
:param sess: TensorFlow session
:param n_images: Number of Images to display
:param input_z: Input Z Tensor
:param out_channel_dim: The number of channels in the output image
:param image_mode: The mode to use for images ("RGB" or "L")
"""
cmap = None if image_mode == 'RGB' else 'gray'
z_dim = input_z.get_shape().as_list()[-1]
example_z = np.random.uniform(-1, 1, size=[n_images, z_dim])
samples = sess.run(
generator(input_z, out_channel_dim, False),
feed_dict={input_z: example_z})
images_grid = helper.images_square_grid(samples, image_mode)
pyplot.imshow(images_grid, cmap=cmap)
pyplot.show()
Implement train to build and train the GANs. Use the following functions you implemented:
model_inputs(image_width, image_height, image_channels, z_dim)model_loss(input_real, input_z, out_channel_dim)model_opt(d_loss, g_loss, learning_rate, beta1)Use the show_generator_output to show generator output while you train. Running show_generator_output for every batch will drastically increase training time and increase the size of the notebook. It's recommended to print the generator output every 100 batches.
def train(epoch_count, batch_size, z_dim, learning_rate, beta1, get_batches, data_shape, data_image_mode):
"""
Train the GAN
:param epoch_count: Number of epochs
:param batch_size: Batch Size
:param z_dim: Z dimension
:param learning_rate: Learning Rate
:param beta1: The exponential decay rate for the 1st moment in the optimizer
:param get_batches: Function to get batches
:param data_shape: Shape of the data
:param data_image_mode: The image mode to use for images ("RGB" or "L")
"""
# Model inputs
input_real, input_z, learn_rate = model_inputs(image_width=data_shape[1],
image_height=data_shape[2],
image_channels=data_shape[3],
z_dim=z_dim)
# Model loss
d_loss, g_loss = model_loss(input_real=input_real,
input_z=input_z,
out_channel_dim=data_shape[3])
# Model optimizer
d_opt, g_opt = model_opt(d_loss=d_loss,
g_loss=g_loss,
learning_rate=learn_rate,
beta1=beta1)
# Train saver
train_saver = tf.train.Saver()
# The number of batches to show images
show_images = 100
# Number of batches to print loss
print_loss = 25
# Training iterations
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for epoch_i in range(epoch_count):
# Batch count for generating images
batch_count = 0
for batch_images in get_batches(batch_size):
# Batch count update
batch_count += 1
# Scaling batch_images to [-1, 1]
batch_images_scaled = 2 * batch_images
# Random data for the generator input
z_input = np.random.uniform(-1, 1, size=(batch_size, z_dim))
# Optimizers and losses calculation
_, train_d_loss = sess.run([d_opt, d_loss], feed_dict={input_real: batch_images_scaled,
input_z: z_input,
learn_rate: learning_rate})
_, train_g_loss = sess.run([g_opt, g_loss], feed_dict={input_z: z_input,
input_real: batch_images_scaled,
learn_rate: learning_rate})
# Printing loss
if batch_count % 10 == 0:
print('Batch: {}, Generator Loss: {:.3f}, Discriminator Loss: {:.3f}'.format(batch_count,
train_g_loss,
train_d_loss
))
# Showing images
if batch_count % 100 == 0:
show_generator_output(sess, 25, input_z, data_shape[3], data_image_mode)
# Saving the model
train_saver.save(sess, './chekpoints/face_gen.ckpt')
print('Model trained and saved')
Test your GANs architecture on MNIST. After 2 epochs, the GANs should be able to generate images that look like handwritten digits. Make sure the loss of the generator is lower than the loss of the discriminator or close to 0.
batch_size = 32
z_dim = 50
learning_rate = 0.0002
beta1 = 0.3
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 2
mnist_dataset = helper.Dataset('mnist', glob(os.path.join(data_dir, 'mnist/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, mnist_dataset.get_batches,
mnist_dataset.shape, mnist_dataset.image_mode)
Run your GANs on CelebA. It will take around 20 minutes on the average GPU to run one epoch. You can run the whole epoch or stop when it starts to generate realistic faces.
batch_size = 32
z_dim = 50
learning_rate = 0.0002
beta1 = 0.3
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
epochs = 1
celeba_dataset = helper.Dataset('celeba', glob(os.path.join(data_dir, 'img_align_celeba/*.jpg')))
with tf.Graph().as_default():
train(epochs, batch_size, z_dim, learning_rate, beta1, celeba_dataset.get_batches,
celeba_dataset.shape, celeba_dataset.image_mode)
When submitting this project, make sure to run all the cells before saving the notebook. Save the notebook file as "dlnd_face_generation.ipynb" and save it as a HTML file under "File" -> "Download as". Include the "helper.py" and "problem_unittests.py" files in your submission.